package lc.oa.ui.fragment;


import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.viewpager.widget.ViewPager;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.RequestFuture;
import com.android.volley.toolbox.Volley;

import org.json.JSONObject;

import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutionException;

import lc.oa.BuildConfig;
import lc.oa.R;
import lc.oa.data.model.LoggedInUser;
import lc.oa.enums.HttpStatus;
import lc.oa.model.RResult;
import lc.oa.net.http.HttpQueueHelper;
import lc.oa.net.http.request.GsonRequest;
import lc.oa.net.ws.OAWebSocketListener;
import lc.oa.net.ws.WebSocketHandler;
import lc.oa.ui.base.BaseFragment;
import lombok.SneakyThrows;
import okhttp3.WebSocket;
import okio.ByteString;

/**
 * @Description: 业绩主页
 * @Author: lucifer
 * @CreateDate: 2020/8/7 14:01
 * @UpdateUser:
 * @UpdateDate:
 * @UpdateRemark:
 * @Version: 1.0
 */
public class AchievementFragment2 extends BaseFragment implements ViewPager.OnPageChangeListener {
    TextView tvException;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_achievement2, container, false);
        tvException = view.findViewById(R.id.tvResponseResult);

        bindEventHandler(view);
        bindWebsocketHandler(view);
        return view;
    }

    //    private Handler handler2=new Handler(){
//        @Override
//        public void handleMessage(Message msg) {
//            switch (msg.what){
//                case 1:
//                    //UI线程
//                    //textView.setText(msg.obj.toString());
//                    tvException.setText(new SimpleDateFormat("yyyy-MM-dd HH:mm.ssss").format(new Date())
//                            +"--->"+msg.obj);
//                case 2:
//                    //UI线程
//                    //textView.setText(msg.obj.toString());
//                    tvException.setText(new SimpleDateFormat("yyyy-MM-dd HH:mm.ssss").format(new Date())
//                            +"--->"+msg.obj);
//                case 3:
//                    //UI线程
//                    //textView.setText(msg.obj.toString());
//                    tvException.setText(new SimpleDateFormat("yyyy-MM-dd HH:mm.ssss").format(new Date())
//                            +"--->"+msg.obj);
//            }
//        }
//    };
    private void bindWebsocketHandler(View view) {
        Button btnConnectWebsocket = view.findViewById(R.id.btnWebSocket);
        // TextView tvException=view.findViewById(R.id.tvResponseResult);
        OAWebSocketListener listeners = new OAWebSocketListener() {
            @Override
            public void onMessage(WebSocket webSocket, String text) {
                Log.d("onMessage", "onMessage(WebSocket webSocket, String text)");
                //    TextView tvException=view.findViewById(R.id.tvResponseResult);
                // tvException.setText(text);
                //切换到UI线程
                Message message = new Message();
                //区分标志
                message.what = 3;
                //传参到ui线程
                message.obj = text;
                handler.sendMessage(message);
            }

            @Override
            public void onMessage(WebSocket webSocket, ByteString bytes) {
                Log.d("onMessage", "onMessage(WebSocket webSocket, ByteString bytes)");
                // TextView tvException=view.findViewById(R.id.tvResponseResult);
                // tvException.setText(bytes.string(Charset.defaultCharset()));
                //切换到UI线程
                Message message = new Message();
                //区分标志
                message.what = 2;
                //传参到ui线程
                message.obj = bytes.string(Charset.defaultCharset());
                handler.sendMessage(message);
            }

            @Override
            public void onOpen(WebSocket webSocket, okhttp3.Response response) {
                //TextView tvException=view.findViewById(R.id.tvResponseResult);
//                tvException.setText(new SimpleDateFormat("yyyy-MM-dd HH:mm.ssss").format(new Date())
//                        +"--->"+response);
                //切换到UI线程
                Message message = new Message();
                //区分标志
                message.what = 1;
                //传参到ui线程
                message.obj = response;
                handler.sendMessage(message);
            }
        };
        btnConnectWebsocket.setOnClickListener(new View.OnClickListener() {
            @SneakyThrows
            @Override
            public void onClick(View v) {

                //同步Post请求必须在子线程中执行
                new Thread(new Runnable() {
                    @SneakyThrows
                    @Override
                    public void run() {
                        RequestQueue requestQueue = Volley.newRequestQueue(getContext());
                        String url = BuildConfig.AUTH_API_URL + "/api/v1/Login/Login";
                        RequestFuture<JSONObject> future = RequestFuture.newFuture();
                        // SignData signData = new SignData();
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("loginType", "10");
                        jsonObject.put("signData", "");
                        jsonObject.put("signVal", "");
                        jsonObject.put("userName", "18311329010");
                        jsonObject.put("userPassword", "82273a6ba2126d3af24ce2d0cb0af515");
                        JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, jsonObject, future, future);
                        requestQueue.add(request);
                        JSONObject response = null;
                        try {
                            response = future.get(); // this will block
                            if (Integer.parseInt(response.get("code") + "") == HttpStatus.OK.getCode().intValue()) {
                                Log.d("登录信息", "登录成功!");

                                JSONObject data = response.getJSONObject("data");
                                String userId = data.getString("userId");
                                String token = data.getString("tokenMsg");
                                Log.i("Web socket test", "Web socket test");

                                LoggedInUser users = new LoggedInUser();
                                users.setUserId(userId);
                                users.setToken(token);

                                Message message = new Message();
                                //区分标志
                                message.what = -1;
                                //传参到ui线程
                                message.obj = users;
                                handler.sendMessage(message);

                                WebSocketHandler webSocketHandler = WebSocketHandler.getInstance(listeners);
//                String token="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjb3JwSWQiOm51bGwsImNvcnBOYW1lIjpudWxsLCJlbmFibGVkIjowLCJleHBpcmUiOjE1OTc2NTQ0NjcwMjgsImlzVUtleUNoZWNrIjowLCJtb2JpbGUiOiIxODMxMTMyOTAxMCIsInJvbGUiOjAsInRpbWUiOjAsInVzZXJJZCI6ImRmYjA0MWI5MGRiMjQ5NTNiNjA1YjZjN2U2ZjQyYzM1IiwidXNlck5hbWUiOiLlvKDmmZPmnpcifQ.XBn3dVjjkP_QP_jFWHx41PS-9ZC_pCEgZnQcZ59kkJI";
                                webSocketHandler.connect(token);
                            }
                        } catch (InterruptedException e) {
                            // exception handling
                            e.printStackTrace();
                        } catch (ExecutionException e) {
                            // exception handling
                            e.printStackTrace();
                        }
//                catch (TimeoutException e) {
//                    e.printStackTrace();
//                }
                        Log.d("响应结果", response.toString());
                    }
                }).start();


//
//                WebSocketHandler webSocketHandler =WebSocketHandler.getInstance(listeners);
//                String token="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjb3JwSWQiOm51bGwsImNvcnBOYW1lIjpudWxsLCJlbmFibGVkIjowLCJleHBpcmUiOjE1OTc2NTQ0NjcwMjgsImlzVUtleUNoZWNrIjowLCJtb2JpbGUiOiIxODMxMTMyOTAxMCIsInJvbGUiOjAsInRpbWUiOjAsInVzZXJJZCI6ImRmYjA0MWI5MGRiMjQ5NTNiNjA1YjZjN2U2ZjQyYzM1IiwidXNlck5hbWUiOiLlvKDmmZPmnpcifQ.XBn3dVjjkP_QP_jFWHx41PS-9ZC_pCEgZnQcZ59kkJI";
//                webSocketHandler.connect(token);
            }
        });
    }

    /**
     * @param
     * @return
     * @method 绑定事件处理
     * @description 服务交互测试
     * @date: 2020/8/7 14:02
     * @author: lucifer
     */
    private void bindEventHandler(View view) {
        TextView tvResponseResult = view.findViewById(R.id.tvResponseResult);
        Button btnJson = view.findViewById(R.id.buttonJson);
        btnJson.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //   String url="https://oa-dev.lecarlink.com/lc.oa.service/test/test";
                //    String url="http://192.168.1.10:60010/lc.secret.service/test/test2";
                // String url= BuildConfig.API_URL+"/test/test2";
                String url = BuildConfig.API_URL + getString(R.string.test);
                Response.Listener listerSuccess = new Response.Listener() {
                    @SuppressLint("LongLogTag")
                    @Override
                    public void onResponse(Object response) {
                        Log.e("---------响应日志-------------", "请求成功!");
                        Log.e("---------响应日志-------------", "响应数据-->" + response.toString());
                        tvResponseResult.setText(new SimpleDateFormat("yyyy-MM-dd HH:mm.ssss").format(new Date())
                                + "--->" + response.toString());
                    }
                };
                Response.ErrorListener errLister = new Response.ErrorListener() {
                    @SuppressLint("LongLogTag")
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.i("---------响应日志-------------", "响应失败!", error);
                        error.printStackTrace();
                    }
                };

//                Map<String, String> header=new HashMap<>();
//                header.put("Content-Type","application/json");
//                header.put("Content-Type","text/html;charset=UTF-8");
//header=null;
                // GsonRequest<RResult> gsonRequest=new GsonRequest<RResult>(url, RResult.class,null,listerSuccess,errLister);
                GsonRequest<RResult> gsonRequest = new GsonRequest<RResult>(url, RResult.class, null, listerSuccess, errLister);
                HttpQueueHelper.getInstance(getContext()).addToRequestQueue(gsonRequest);
            }
        });
        Button btnNonJson = view.findViewById(R.id.buttonNonJson);
        btnNonJson.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String url = "https://oa-dev.lecarlink.com/lc.oa.service/test/test";
                // String url="http://192.168.1.10:60010/lc.secret.service/test/test2";
                Response.Listener listerSuccess = new Response.Listener() {
                    @SuppressLint("LongLogTag")
                    @Override
                    public void onResponse(Object response) {
                        Log.e("---------响应日志-------------", "请求成功!");
                        Log.e("---------响应日志-------------", "响应数据-->" + response.toString());
                    }
                };
                Response.ErrorListener errLister = new Response.ErrorListener() {
                    @SuppressLint("LongLogTag")
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.i("---------响应日志-------------", "响应失败!", error);
                        error.printStackTrace();
                    }
                };

//                Map<String, String> header=new HashMap<>();
//                header.put("Content-Type","application/json");
//                header.put("Content-Type","text/html;charset=UTF-8");
//header=null;
                // GsonRequest<RResult> gsonRequest=new GsonRequest<RResult>(url, RResult.class,null,listerSuccess,errLister);
                GsonRequest<String> gsonRequest = new GsonRequest<String>(url, String.class, null, listerSuccess, errLister);
                HttpQueueHelper.getInstance(getContext()).addToRequestQueue(gsonRequest);
            }
        });
        Button btnNonJson2 = view.findViewById(R.id.buttonNonJson2);
        btnNonJson2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String url = "http://192.168.1.10:60010/lc.secret.service/test/test3";
                // String url="http://192.168.1.10:60010/lc.secret.service/test/test2";
                Response.Listener listerSuccess = new Response.Listener() {
                    @SuppressLint("LongLogTag")
                    @Override
                    public void onResponse(Object response) {
                        Log.e("---------响应日志-------------", "请求成功!");
                        Log.e("---------响应日志-------------", "响应数据-->" + response.toString());
                    }
                };
                Response.ErrorListener errLister = new Response.ErrorListener() {
                    @SuppressLint("LongLogTag")
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.i("---------响应日志-------------", "响应失败!", error);
                        error.printStackTrace();
                    }
                };

//                Map<String, String> header=new HashMap<>();
//                header.put("Content-Type","application/json");
//                header.put("Content-Type","text/html;charset=UTF-8");
//header=null;
                // GsonRequest<RResult> gsonRequest=new GsonRequest<RResult>(url, RResult.class,null,listerSuccess,errLister);
                GsonRequest<RResult> gsonRequest = new GsonRequest<RResult>(url, RResult.class, null, listerSuccess, errLister);
                HttpQueueHelper.getInstance(getContext()).addToRequestQueue(gsonRequest);

            }
        });
    }

    //UI线程
    @Override
    protected void handlerMessage1(Message msg) {
        switch (msg.what) {
            case 1:
                //UI线程
                //textView.setText(msg.obj.toString());
                tvException.setText(new SimpleDateFormat("yyyy-MM-dd HH:mm.ssss").format(new Date())
                        + "--->" + msg.obj);
            case 2:
                //UI线程
                //textView.setText(msg.obj.toString());
                tvException.setText(new SimpleDateFormat("yyyy-MM-dd HH:mm.ssss").format(new Date())
                        + "--->" + msg.obj);
            case 3:
                //UI线程
                //textView.setText(msg.obj.toString());
                tvException.setText(new SimpleDateFormat("yyyy-MM-dd HH:mm.ssss").format(new Date())
                        + "--->" + msg.obj);
            case -1:
                Toast.makeText(getContext(),msg.obj.toString(),Toast.LENGTH_SHORT).show();
                break;
        }
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initControl() {

    }

    @Override
    public void onModeChanged(int action, Object... values) {

    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
}
